package com.linsen.core.rule.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.linsen.core.redis.service.RedisService;
import com.linsen.core.rule.constant.RuleConstant;
import com.linsen.core.rule.model.Deny;
import com.linsen.core.rule.service.IRuleCacheService;
import lombok.RequiredArgsConstructor;

import java.util.Set;

/**
 * 规则缓存实现业务类
 * @author zhaoyong
 * @date 2023/3/13
 */
@RequiredArgsConstructor
public class RuleCacheServiceImpl implements IRuleCacheService {
    private final RedisService redisService;

    @Override
    public Set<Object> getDenys(String ip) {
        return redisService.sGet(RuleConstant.getDenyCacheKey(ip));
    }

    @Override
    public Set<Object> getDenys() {
        return redisService.sGet(RuleConstant.getDenyCacheKey());
    }

    @Override
    public void setDeny(Deny deny) {
        String key = StrUtil.isNotBlank(deny.getIp()) ? RuleConstant.getDenyCacheKey(deny.getIp())
                : RuleConstant.getDenyCacheKey();
        redisService.sSet(key, JSONObject.toJSONString(deny));
    }

    @Override
    public void deleteDeny(Deny deny) {
        String key = StrUtil.isNotBlank(deny.getIp()) ? RuleConstant.getDenyCacheKey(deny.getIp())
                : RuleConstant.getDenyCacheKey();
        redisService.setRemove(key, JSONObject.toJSONString(deny));
    }
}